<template>
	<div class="order-success-page">
		<!-- 顶部标签 -->
		<div class="tabs">
			<text class="tab-item" :class="{active: currentTab === 'activity'}" @click="switchTab('activity')">活动</text>
			<text class="tab-item" :class="{active: currentTab === 'product'}" @click="switchTab('product')">商品</text>
		</div>

		<!-- 订单列表 -->
		<div class="order-list-container">
			<!-- 商品订单 -->
			<div class="order-card-wrapper" v-if="currentTab === 'product'">
				<div class="order-card" v-for="(order, index) in orderList" :key="index">
					<div class="order-header" @click="ckxq(order)">
						<text class="order-id">订单编号：{{order.order_sn}}</text>
						<text class="order-status" style="color: orangered;" v-if="order.order_status==0">待支付</text>
						<text class="order-status" v-if="order.order_status==10">待发货</text>
						<text class="order-status" v-if="order.order_status==4">待收货</text>
						<text class="order-status" style="color: #ff692f;" v-if="order.order_status==-1">退款中</text>
						<text class="order-status" style="color: red;" v-if="order.order_status==-2">拒绝退款</text>
						<text class="order-status" style="color: darkgray;" v-if="order.order_status==-10">已退款</text>
						<text class="order-status" style="color: #232323;" v-if="order.order_status==20">已完成</text>
						<text class="order-status" style="color: #232323;" v-if="order.order_status==-20">已取消</text>
					</div>

					<!-- 商品列表 -->
					<div class="product-list" @click="ckxq(order)">
						<div class="product-info" v-for="(item, idx) in order.goods_order_list" :key="idx">
							<img class="product-img" :src="item.goods_cover_path" alt="商品图片">
							<div class="product-details">
								<div class="product-name">{{item.goods_name}}</div>
								<div class="product-price" style="display: flex;justify-content: space-between;">
									<div>
										<text class="price-symbol">¥</text>
										<text class="price-value">{{item.goods_price}}</text>
									</div>
									<div><text class="product-quantity">x{{item.purchase_quantity}}</text></div>
								</div>
							</div>
						</div>
					</div>

					<div class="order-footer" @click="ckxq(order)">
						<text class="order-time">下单时间：{{order.created_at}}</text>
						<text class="order-paid">实付：<text class="paid-amount">¥{{order.total_price}}</text></text>
					</div>

					<!-- 操作按钮 -->
					<div class="action-buttons">
						<div class="action-btn refund-btn" v-if="order.order_status==10" @click.stop="showRefundDialog(order, 'goods')">申请退款</div>
						<div class="action-btn next-btn" v-if="order.order_status==10" @click.stop="ddqrfun(order,'0')">再下一单</div>
						<div class="action-btn next-btn" v-if="order.order_status==4||order.order_status==10" @click.stop="showConfirmReceiptDialog(order)">确认收货</div>
						<div class="action-btn refund-btn" v-if="order.order_status==0" @click.stop="ddqrfun(order,'1')">去支付</div>
						<div class="action-btn refund-btn"
							v-if="order.order_status==-1||order.order_status==-2||order.order_status==-10||order.order_status==20||order.order_status==-20" @click.stop="ckxq(order)">查看详情</div>
					</div>
				</div>
				
				<!-- 加载更多 -->
				<div class="load-more" v-if="productPage.loading">{{productPage.loadingText}}</div>
				<div class="no-more" v-if="productPage.noMore">没有更多数据了</div>
			</div>

			<!-- 活动订单 -->
			<div class="order-card-wrapper" v-if="currentTab === 'activity'">
				<div class="order-card" v-for="(order, index) in hdorderList" :key="index">
					<div class="order-header" @click="hdckxq(order)">
						<text class="order-id">订单编号：{{order.activity_order_sn}}</text>
						<text class="order-status" style="color: orangered;" v-if="order.activity_order_status==0">待支付</text>
						<text class="order-status" v-if="order.activity_order_status==10">已支付</text>
						<text class="order-status" style="color: #ff692f;" v-if="order.activity_order_status==-1">退款中</text>
						<text class="order-status" style="color: red;" v-if="order.activity_order_status==-2">拒绝退款</text>
						<text class="order-status" style="color: darkgray;" v-if="order.activity_order_status==-10">已退款</text>
					</div>

					<!-- 活动列表 -->
					<div class="product-list" @click="hdckxq(order)">
						<div class="product-info">
							<img class="product-img" :src="order.activity_cover_path" alt="活动图片">
							<div class="product-details">
								<div class="product-name">{{order.activity_title}}</div>
								<div class="product-price" style="display: flex;justify-content: space-between;">
									<div><text class="product-quantity">{{ order.activity_spec_data.activity_end_at }}-{{ order.activity_spec_data.activity_start_at }}</text></div>
									<div>
										<text class="price-symbol">¥</text>
										<text class="price-value">{{order.total_activity_price}}</text>
									</div>
								</div>
							</div>
						</div>
					</div>

					<div class="order-footer" @click="hdckxq(order)">
						<text class="order-time">下单时间：{{order.updated_at}}</text>
						<text class="order-paid">实付：<text class="paid-amount">¥{{order.total_activity_price}}</text></text>
					</div>

					<!-- 操作按钮 -->
					<div class="action-buttons">
						<div class="action-btn refund-btn" v-if="order.activity_order_status==10" @click.stop="showRefundDialog(order, 'activity')">申请退款</div>
						<div class="action-btn refund-btn"
						
							v-if="order.activity_order_status==-1||order.activity_order_status==-2||order.activity_order_status==-10" @click="hdckxq(order)">查看详情</div>
					</div>
				</div>
				
				<!-- 加载更多 -->
				<div class="load-more" v-if="activityPage.loading">{{activityPage.loadingText}}</div>
				<div class="no-more" v-if="activityPage.noMore">没有更多数据了</div>
			</div>
		</div>

		<!-- 退款申请弹框 -->
		<uni-popup ref="refundPopup" type="center">
			<div class="refund-popup">
				<div class="popup-header">
					<text class="popup-title">申请退款</text>
					<text class="popup-close" @click="closeRefundDialog">×</text>
				</div>
				<div class="popup-content">
					<div class="refund-order-info">
						<text>订单编号：{{currentOrder.order_sn || currentOrder.activity_order_sn}}</text>
						<text>订单金额¥{{currentOrder.total_price || currentOrder.total_activity_price}}</text>
					</div>
					<div class="refund-reason">
						<text class="reason-label">退款原因</text>
						<textarea 
							class="reason-input" 
							v-model="refundReason" 
							placeholder="请输入退款原因（必填）"
							placeholder-style="color:#999;font-size:14px;"
						></textarea>
					</div>
				</div>
				<div class="popup-footer">
					<button class="cancel-btn" @click="closeRefundDialog">取消</button>
					<button class="confirm-btn" @click="submitRefund">提交申请</button>
				</div>
			</div>
		</uni-popup>

		<!-- 确认收货弹框 -->
		<uni-popup ref="confirmReceiptPopup" type="center">
			<div class="refund-popup">
				<div class="popup-content">
					<div class="refund-order-info">
						<text>订单编号：{{currentOrder.order_sn}}</text>
						<text>订单金额：¥{{currentOrder.total_price}}</text>
					</div>
				</div>
				<div class="popup-footer">
					<button class="cancel-btn" @click="closeConfirmReceiptDialog">取消</button>
					<button class="confirm-btn" @click="submitConfirmReceipt">确认收货</button>
				</div>
			</div>
		</uni-popup>
	</div>
</template>

<script>
	import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
	import {
		order_getGoodsOrderList,
		order_confirmGoodsOrderInfo,
		order_applyRefund,
		order_confirmReceipt,
		order_getActivityOrderList,
		order_applyActivityRefund
	} from '@/api/system/user.js'
	
	export default {
		name: 'OrderSuccessPage',
		components: { uniPopup },
		data() {
			return {
				currentTab: 'activity',
				hdorderList: [],
				orderList: [],
				currentOrder: {}, // 当前操作的订单
				refundReason: '', // 退款原因
				refundType: '', // 退款类型：goods 或 activity
				productPage: {
					page: 1,
					size: 10,
					loading: false,
					noMore: false,
					loadingText: '加载中...'
				},
				activityPage: {
					page: 1,
					size: 10,
					loading: false,
					noMore: false,
					loadingText: '加载中...'
				}
			}
		},
		created() {
			this.loadOrders();
		},
		onReachBottom() {
			// 滚动到底部加载更多
			if (this.currentTab === 'product' && !this.productPage.noMore && !this.productPage.loading) {
				this.productPage.page++;
				this.order_getGoodsOrderList();
			} else if (this.currentTab === 'activity' && !this.activityPage.noMore && !this.activityPage.loading) {
				this.activityPage.page++;
				this.order_getActivityOrderList();
			}
		},
		methods: {
			switchTab(tab) {
				this.currentTab = tab;
				// 切换标签时检查是否需要加载数据
				if (tab === 'product' && this.orderList.length === 0 && !this.productPage.noMore) {
					this.order_getGoodsOrderList();
				} else if (tab === 'activity' && this.hdorderList.length === 0 && !this.activityPage.noMore) {
					this.order_getActivityOrderList();
				}
			},
			
			async loadOrders() {
				// 初始加载两种订单
				await Promise.all([
					this.order_getGoodsOrderList(),
					this.order_getActivityOrderList()
				]);
			},
			
			async order_getGoodsOrderList() {
				if (this.productPage.noMore || this.productPage.loading) return;
				
				this.productPage.loading = true;
				this.productPage.loadingText = '加载中...';
				
				try {
					const data = await order_getGoodsOrderList({
						page: this.productPage.page,
						size: this.productPage.size
					});
					
					if (data.code === 200) {
						if (this.productPage.page === 1) {
							this.orderList = data.content.data || [];
						} else {
							this.orderList = [...this.orderList, ...(data.content.data || [])];
						}
						
						// 检查是否还有更多数据
						if (!data.content.data || data.content.data.length < this.productPage.size) {
							this.productPage.noMore = true;
							this.productPage.loadingText = '没有更多数据了';
						}
					} else {
						this.productPage.loadingText = '加载失败，点击重试';
					}
				} catch (error) {
					this.productPage.loadingText = '加载失败，点击重试';
					console.error('加载商品订单失败:', error);
				} finally {
					this.productPage.loading = false;
				}
			},
			
			async order_getActivityOrderList() {
				if (this.activityPage.noMore || this.activityPage.loading) return;
				
				this.activityPage.loading = true;
				this.activityPage.loadingText = '加载中...';
				
				try {
					const data = await order_getActivityOrderList({
						page: this.activityPage.page,
						size: this.activityPage.size
					});
					
					if (data.code === 200) {
						if (this.activityPage.page === 1) {
							this.hdorderList = data.content.data || [];
						} else {
							this.hdorderList = [...this.hdorderList, ...(data.content.data || [])];
						}
						
						// 检查是否还有更多数据
						if (!data.content.data || data.content.data.length < this.activityPage.size) {
							this.activityPage.noMore = true;
							this.activityPage.loadingText = '没有更多数据了';
						}
					} else {
						this.activityPage.loadingText = '加载失败，点击重试';
					}
				} catch (error) {
					this.activityPage.loadingText = '加载失败，点击重试';
					console.error('加载活动订单失败:', error);
				} finally {
					this.activityPage.loading = false;
				}
			},
			
			async ddqrfun(e,m) {
				let a=[];
				for (let i = 0; i < e.goods_order_list.length; i++) {
					a.push({
						goods_id: e.goods_order_list[i].goods_id,
						purchase_quantity: e.goods_order_list[i].purchase_quantity
					})
				}
				const data = await order_confirmGoodsOrderInfo({goods_arr:a})
				if(data.code==200){
					let c={
						order_sn:m==1?e.order_sn:'',
						data:data.content.data
					}
					const params = encodeURIComponent(JSON.stringify(c));
					  uni.navigateTo({
					    url: `/pages/orderConfirmation?data=${params}`
					  });
				} 
			},
			
			async ckxq(e,m) {
				if(e.order_status==10||e.order_status==-1||e.order_status==-2||e.order_status==-10||e.order_status==20){
					let c={
						order_sn:e.order_sn,
					}
					const params = encodeURIComponent(JSON.stringify(c));
					  uni.navigateTo({
					    url: `/pages/orderConfirmations?data=${params}`
					  });
				}else{
					let a=[];
					for (let i = 0; i < e.goods_order_list.length; i++) {
						a.push({
							goods_id: e.goods_order_list[i].goods_id,
							purchase_quantity: e.goods_order_list[i].purchase_quantity
						})
					}
					const data = await order_confirmGoodsOrderInfo({goods_arr:a})
					if(data.code==200){
						let c={
							order_sn:m==1?e.order_sn:'',
							data:data.content.data
						}
						const params = encodeURIComponent(JSON.stringify(c));
						  uni.navigateTo({
						    url: `/pages/orderConfirmation?data=${params}`
						  });
					} 
				}
			},
			hdckxq(e){
				let c={
					activity_order_sn:e.activity_order_sn,
				}
				const params = encodeURIComponent(JSON.stringify(c));
				  uni.navigateTo({
				    url: `/pages/activityConfirmations?data=${params}`
				  });
			},
			hdxiangq() {
				uni.navigateTo({
					url: `/pages/activityDeatails?name=${encodeURIComponent('美学设计')}`
				});
			},
			
			// 显示退款弹框
			showRefundDialog(order, type) {
				this.currentOrder = order;
				this.refundReason = '';
				this.refundType = type;
				this.$refs.refundPopup.open();
			},
			
			// 关闭退款弹框
			closeRefundDialog() {
				this.$refs.refundPopup.close();
			},
			
			// 提交退款申请
			async submitRefund() {
				if (!this.refundReason.trim()) {
					uni.showToast({
						title: '请填写退款原因',
						icon: 'none'
					});
					return;
				}
				
				try {
					let apiMethod='';
					const params = {
						refund_reason: this.refundReason
					};
					
					if (this.refundType === 'goods') {
						params.order_sn = this.currentOrder.order_sn;
						apiMethod = order_applyRefund;
					} else {
						params.activity_order_sn = this.currentOrder.activity_order_sn;
						apiMethod = order_applyActivityRefund; 
					}
					
					const data = await apiMethod(params);
					
					if (data.code === 200) {
						uni.showToast({
							title: '退款申请已提交',
							icon: 'success'
						});
						this.closeRefundDialog();
						// 刷新订单列表
						if (this.currentTab === 'product') {
							this.productPage.page = 1;
							this.productPage.noMore = false;
							this.order_getGoodsOrderList();
						} else {
							this.activityPage.page = 1;
							this.activityPage.noMore = false;
							this.order_getActivityOrderList();
						}
					} else {
						uni.showToast({
							title: data.msg || '退款申请失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				}
			},
			
			// 显示确认收货弹框
			showConfirmReceiptDialog(order) {
				this.currentOrder = order;
				this.$refs.confirmReceiptPopup.open();
			},
			
			// 关闭确认收货弹框
			closeConfirmReceiptDialog() {
				this.$refs.confirmReceiptPopup.close();
			},
			
			// 提交确认收货
			async submitConfirmReceipt() {
				try {
					const data = await order_confirmReceipt({
						order_sn: this.currentOrder.order_sn
					});
					
					if (data.code === 200) {
						uni.showToast({
							title: '确认收货成功',
							icon: 'success'
						});
						this.closeConfirmReceiptDialog();
						// 刷新订单列表
						this.productPage.page = 1;
						this.productPage.noMore = false;
						this.order_getGoodsOrderList();
					} else {
						uni.showToast({
							title: data.msg || '确认收货失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.order-success-page {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.tabs {
		display: flex;
		padding: 12px 0;
		background: #fff;
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		color: #666;
		font-size: 16px;
		position: relative;
		padding: 8px 0;
	}

	.tab-item.active {
		color: #07c160;
		font-weight: 500;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: -4px;
		left: 50%;
		transform: translateX(-50%);
		width: 24px;
		height: 3px;
		background: #07c160;
		border-radius: 3px;
	}

	.order-list-container {
		padding: 12px;
	}

	.order-card-wrapper {
		width: 100%;
	}

	.order-card {
		background: #fff;
		border-radius: 12px;
		padding: 16px;
		margin-bottom: 12px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
	}

	.order-header {
		display: flex;
		    justify-content: space-between;
		    padding-bottom: 16px;
		    border-bottom: 1px solid #f0f0f0;
		    align-items: center;
		    /* 新增：防止挤压 */
		    min-width: 0;
	}

	.order-id {
		color: #999;
		    font-size: 14px;
		    /* 新增：省略号样式 */
		    flex: 1;
		    overflow: hidden;
		    text-overflow: ellipsis;
		    white-space: nowrap;
		    min-width: 0;
		    max-width: 60%; /* 可根据实际情况调整 */
	}

	.order-status {
		font-size: 14px;
		    font-weight: 500;
		    /* 新增：防止挤压 */
		    flex-shrink: 0;
		    margin-left: 10px;
	}

	.product-list {
		margin-top: 16px;
	}

	.product-info {
		display: flex;
		padding: 12px 0;
	}

	.product-img {
		width: 80px;
		height: 80px;
		border-radius: 6px;
		object-fit: cover;
		flex-shrink: 0;
	}

	.product-details {
		flex: 1;
		margin-left: 12px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-name {
		font-size:15px;
		color: #333;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		text-overflow: ellipsis;
		word-break: break-all;
		line-height: 1.4;
	}

	.product-price {
		display: flex;
		justify-content: space-between;
		width: 100%;
		align-items: center;
	}

	.price-symbol {
		font-size: 12px;
		color: #ff4444;
	}

	.price-value {
		font-size: 16px;
		font-weight: 500;
		color: #ff4444;
	}

	.product-quantity {
		color: #999;
		font-size: 14px;
	}

	.order-footer {
		display: flex;
		justify-content: space-between;
		padding: 16px 0;
		font-size: 14px;
		border-top: 1px solid #f0f0f0;
		margin-top: 8px;

		.order-time {
			color: #999;
		}

		.order-paid {
			font-weight: 500;
			font-size: 14px;
		}
	}

	.paid-amount {
		font-weight: 600;
		font-size: 16px;
		color: #ff4444;
	}

	.action-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
		margin-top: 16px;
		padding-top: 12px;
		border-top: 1px solid #f0f0f0;
	}

	.action-btn {		padding: 0 16px;
		height: 32px;
		border-radius: 16px;
		font-size: 13px;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px solid #ddd;
	}

	.refund-btn {
		background: #fff;
		color: #666;
		border-color: #ddd;
	}

	.next-btn {
		background: #07c160;
		color: #fff;
		border-color: #07c160;
	}

	.load-more, .no-more {
		text-align: center;
		padding: 12px;
		color: #999;
		font-size: 14px;
	}

	.no-more {
		color: #ccc;
	}

	/* 退款弹框样式 */
	.refund-popup {
		width: 85vw;
		background-color: #fff;
		border-radius: 16px;
		overflow: hidden;
		max-width: 400px;
	}

	.popup-header {
		position: relative;
		padding: 18px 15px;
		text-align: center;
		border-bottom: 1px solid #f5f5f5;
	}

	.popup-title {
		font-size: 18px;
		font-weight: 500;
		color: #333;
	}

	.popup-close {
		position: absolute;
		right: 15px;
		top: 50%;
		transform: translateY(-50%);
		font-size: 28px;
		color: #999;
		line-height: 1;
	}

	.popup-content {
		padding: 15px;
		max-height: 60vh;
		overflow-y: auto;
	}

	.refund-order-info {
		display: flex;
		flex-direction: column;
		gap: 8px;
		margin-bottom: 15px;
		font-size: 14px;
		color: #666;
		background: #f9f9f9;
		padding: 12px;
		border-radius: 8px;
	}

	.refund-order-info text {
		word-break: break-all;
	}

	.refund-reason {
		margin-bottom: 15px;
	}

	.reason-label {
		display: block;
		margin-bottom: 8px;
		font-size: 15px;
		color: #333;
		font-weight: 500;
	}

	.reason-input {
		width: 100%;
		min-height: 100px;
		padding: 10px;
		border: 1px solid #eee;
		border-radius: 8px;
		font-size: 14px;
		box-sizing: border-box;
		background-color: #fff;
	}

	.popup-footer {
		display: flex;
		border-top: 1px solid #f5f5f5;
	}

	.popup-footer button {
		flex: 1;
		height: 50px;
		line-height: 50px;
		text-align: center;
		font-size: 16px;
		border: none;
		border-radius: 0;
		background: none;
	}

	.popup-footer button::after {
		border: none;
	}

	.cancel-btn {
		color: #666;
		border-right: 1px solid #f5f5f5 !important;
	}

	.confirm-btn {
		color: #07c160;
		font-weight: 500;
	}
</style>